<?php

namespace app\data\controller\api\auth;

use app\data\controller\api\Auth;
use app\data\service\CouponService;

/**
 * 优惠券接口
 * Class Coupon
 * @package app\data\controller\api\auth
 */
class Coupon extends Auth
{
    /**
     * 控制器初始化
     */
    protected function initialize()
    {
        parent::initialize();
        if (empty($this->user['status'])) {
            $this->error('账户已被冻结，不能操作优惠券哦！');
        }
    }

    /**
     * @api            {get} data/api/coupon
     * @apiName        优惠券列表
     * @apiStatus      working
     * @apiDescription 优惠券列表-描述
     * @apiPermission  token
     * @apiParam {integer} [status] 状态筛选(0=未使用;1=已使用;2=已失效)
     * @apiParam {integer} [type] 类型(new=新人券;common=普通券;special=指定券)
     * @apiParam {integer} [is_show] 是否显示过(0=否;1=是)
     * @apiSuccess {object} data={car_user_coupons}
     * @apiSuccess {string} data.status_text 状态文字描述(0=未使用;1=已使用;2=已失效)
     * @apiSuccess {string} data.type_text 类型文字描述(new=新人券;common=普通券;special=指定券)
     * @apiSuccess {string} data.min_use_amount_text 使用门槛文字描述
     * @apiSuccess {string} data.end_time_text 可用日期文字描述
     */
    public function get()
    {
        $status = input('status', '');
        $type = input('type', '');
        $isShow = input('is_show', '');

        if ($status !== '') {
            if ($status == '1') {
                $map[] = ['is_use', '=', 1];
            } else if ($status == '2') {
                $map[] = ['is_use', '=', 0];
                $map[] = ['end_time', '<', date('Y-m-d H:i:s')];
            } else {
                $map[] = ['is_use', '=', 0];
                $map[] = ['end_time', '>=', date('Y-m-d H:i:s')];
            }
        }

        if ($type !== '') {
            $type = explode(',', $type);
            $map[] = ['type', 'in', $type];
        }

        if ($isShow !== '') {
            $map[] = ['is_show', '=', $isShow];
        }

        $map[] = ['uuid', '=', $this->uuid];

        $result = $this->_query('car_user_coupons')
            ->where($map)
            ->order('id desc')
            ->page(true, false, false, 20);

        foreach ($result['list'] as &$vo) {
            $vo = CouponService::instance()->formatCoupon($vo);
        }

        if (!$isShow && !empty($result['list'])) {
            $this->_query('car_user_coupons')
                ->where('uuid', $this->uuid)
                ->update(['is_show' => 1]);
        }

        $this->success('获取优惠券列表成功！', $result);
    }

    /**
     * @api            {get} data/api/can-use-coupon
     * @apiName        可用优惠券列表
     * @apiStatus      working
     * @apiDescription 可用优惠券列表-描述
     * @apiPermission  token
     * @apiParam {integer} [car_info_id] 年审车辆ID
     * @apiParam {integer} [car_monitoring_station_id] 检测站ID
     * @apiParam {string} [province] 省
     * @apiParam {string} [city] 市
     * @apiParam {string} [area] 区
     * @apiSuccess {object} data={car_user_coupons}
     * @apiSuccess {string} data.status_text 状态文字描述(0=未使用;1=已使用;2=已失效)
     * @apiSuccess {string} data.type_text 类型文字描述(new=新人券;common=普通券;special=指定券)
     * @apiSuccess {string} data.min_use_amount_text 使用门槛文字描述
     * @apiSuccess {string} data.end_time_text 可用日期文字描述
     * @apiSuccess {string} data.can_use 状态文字描述(0=不可用;1=可用)
     */
    public function canUse()
    {
        $data = $this->_vali([
            'uuid.value'            => $this->uuid,
            'car_info_id.default'      => 0,
            'car_monitoring_station_id.default'      => 0,
            'province.default'     => '',
            'city.default'     => '',
            'area.default'     => '',
        ]);

        $carInfo = $this->app->db->name('car_infos')->where('id', $data['car_info_id'])->findOrEmpty();
        if (!empty($carInfo)) {
            $rule = $this->app->db->name('CarBasePrice')
                ->where('vehicle_type', $carInfo['vehicle_type'])
                ->where('fuel_type', $carInfo['fuel_type'])
                ->where('province', $data['province'])
                ->where('city', $data['city'])
                ->order('sort desc,id desc')->findOrEmpty();
            if (empty($rule)) {
                $total = sysconf('data.base_price');
            } else {
                $total = $rule['price'];
            }
        } else {
            $total = 0;
        }


        $map[] = ['uuid', '=', $this->uuid];
        $map[] = ['is_use', '=', 0];
        $map[] = ['end_time', '>=', date('Y-m-d H:i:s')];
        $result = $this->_query('car_user_coupons')
            ->where($map)
            ->order('id desc')
            ->page(true, false, false, 20);

        foreach ($result['list'] as &$vo) {
            $vo['can_use'] = 1;

            if ($vo['min_use_amount'] >= $total) {
                $vo['can_use'] = 0;
            }

            $vehicleTypes = $vo['vehicle_types'];
            if (!is_null($vehicleTypes) && $vehicleTypes !== '') {
                $vehicleTypes = explode(',', $vehicleTypes);
                if (!in_array($carInfo['vehicle_type'], $vehicleTypes)) {
                    $vo['can_use'] = 0;
                }
            }

            $monitoringStations = $vo['monitoring_stations'];
            if (!is_null($monitoringStations) && $monitoringStations !== '') {
                $monitoringStations = explode(',', $monitoringStations);
                if (!in_array($data['car_monitoring_station_id'], $monitoringStations)) {
                    $vo['can_use'] = 0;
                }
            }

            if (
                empty($data['car_info_id']) ||
                empty($data['car_monitoring_station_id']) ||
                empty($data['province']) ||
                empty($data['city'])
            ) {
                $vo['can_use'] = 0;
            }

            $vo = CouponService::instance()->formatCoupon($vo);
        }

        $this->success('获取可用优惠券列表成功！', $result);
    }

    /**
     * @api            {get} data/api/coupon-list
     * @apiName        待领取的优惠券列表
     * @apiStatus      working
     * @apiDescription 待领取的优惠券列表-描述
     * @apiPermission  token
     * @apiSuccess {object} data={car_coupons}
     * @apiSuccess {string} data.type_text 类型文字描述(new=新人券;common=普通券;special=指定券)
     * @apiSuccess {string} data.min_use_amount_text 使用门槛文字描述
     * @apiSuccess {string} data.end_time_text 可用日期文字描述
     */
    public function couponList()
    {
//        $couponIds = $this->app->db->name('car_user_coupons')->where('uuid', $this->uuid)->field('coupon_id')->select()->toArray();
//        $couponIds = array_column($couponIds, 'coupon_id');
        $result = $this->_query('car_coupons')
//            ->whereNotIn('id', $couponIds)
            ->where('type', 'common')
            ->where('status', 1)
            ->where('stock', '>', 0)
            ->order('id desc')
            ->page(true, false, false, input('limit', 10));

        foreach ($result['list'] as &$vo) {
            $vo = CouponService::instance()->formatCoupon($vo);
        }

        $this->success('获取优惠券列表成功！', $result);
    }

    /**
     * @api            {post} data/api/got-coupon
     * @apiName        领取优惠券
     * @apiStatus      working
     * @apiDescription 领取优惠券-描述
     * @apiPermission  token
     * @apiParam {integer} id 优惠券ID
     * @apiSuccess {object} data
     * @apiSuccess {integer} data.car_user_coupon_id 用户优惠券ID
     */
    public function gotCoupon()
    {
        $data = $this->_vali([
            'uuid.value'            => $this->uuid,
            'id.require'      => '优惠券ID不能为空',
        ]);
        try {
            $userCoupon = CouponService::instance()->gotCoupon($data['id'], $data['uuid']);
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }

        $this->success('领取优惠券成功', ['car_user_coupon_id' => (int)$userCoupon]);
    }
}